using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace Ant2
{

    public class Sprite
    {
        public Rectangle bounds;
        public Color color;
        public Texture2D texture;

        public void Dispose()
        {
            texture.Dispose();
        }

        public Sprite(Texture2D Tex, Rectangle Bounds)
        {
            texture = Tex;
            bounds = Bounds;
            color = Color.White;
        }

        public void Render(SpriteBatch sb)
        {
            sb.Draw(texture, bounds, color);
        }

        public void RenderAt(SpriteBatch sb,Point pt)
        {

            sb.Draw(texture, bounds+pt, color);
        }

        public static bool Intersects(Sprite a, Sprite b)
        {
            if (Collision.Intersects(a.bounds, b.bounds))
            {

                uint[] bitsA = new uint[a.texture.Width * a.texture.Height];
                a.texture.GetData<uint>(bitsA);

                uint[] bitsB = new uint[b.texture.Width * b.texture.Height];
                b.texture.GetData<uint>(bitsB);

                int x1 = Math.Max(a.bounds.X, b.bounds.X);
                int x2 = Math.Min(a.bounds.X + a.bounds.Width, b.bounds.X + b.bounds.Width);

                int y1 = Math.Max(a.bounds.Y, b.bounds.Y);
                int y2 = Math.Min(a.bounds.Y + a.bounds.Height, b.bounds.Y + b.bounds.Height);

                for (int y = y1; y < y2; ++y)
                {
                    for (int x = x1; x < x2; ++x)
                    {
                        if (((bitsA[(x - a.bounds.X) + (y - a.bounds.Y) * a.texture.Width] & 0xFF000000) >> 24) > 20 &&
                            ((bitsB[(x - b.bounds.X) + (y - b.bounds.Y) * b.texture.Width] & 0xFF000000) >> 24) > 20)
                            return true;
                    }
                }
            }

            return false;
        }
    }

    public class Collision
    {

        public static bool Intersects(Rectangle a, Rectangle b)
        {
            // check if two Rectangles intersect
            return (a.Right > b.Left && a.Left < b.Right &&
                    a.Bottom > b.Top && a.Top < b.Bottom);
        }

        public static bool Touches(Rectangle a, Rectangle b)
        {
            // check if two Rectangles intersect or touch sides
            return (a.Right >= b.Left && a.Left <= b.Right &&
                    a.Bottom >= b.Top && a.Top <= b.Bottom);
        }
    }
}
